<template>
  <div class="login-container">
    <div class="login-form">
      <h2>Easy Go 管理系统</h2>
      <el-form
          :model="loginForm"
          :rules="rules"
          ref="loginFormRef"
          label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="loginForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
              v-model="loginForm.password"
              type="password"
              placeholder="请输入密码"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleLogin">登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { ElMessage } from 'element-plus';
import axios from 'axios';
import { useRouter } from 'vue-router';

const router = useRouter();
const loginFormRef = ref(null);
const loginForm = reactive({
  username: 'admin',
  password: '123456'
});

const rules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
};

const handleLogin = async () => {
  const valid = await loginFormRef.value.validate();
  if (!valid) return;

  try {
    const { data } = await axios.post('/api/user/login', {
      username: loginForm.username,
      password: loginForm.password
    });

    if (data.code === 200) {
      ElMessage.success('登录成功');
      // 存储JWT Token到localStorage
      localStorage.setItem('token', data.token);
      router.push('/Dashboard.vue');
    } else {
      ElMessage.error(data.msg || '登录失败');
    }
  } catch (error) {
    ElMessage.error('网络异常或服务器错误');
  }
};
</script>

<style scoped>
/* 样式不变 */
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: #f5f7fa;
}

.login-form {
  width: 400px;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.login-form h2 {
  text-align: center;
  margin-bottom: 20px;
}
</style>